<?php

  function db_connect($host, $user, $pass) {
    return mysql_connect($host, $user, $pass);
  }
  
  function db_close() {
    return mysql_close();
  }
  
  function db_select_db($db_name) {
    return mysql_select_db($db_name);
  }
  
  function db_fetch_array($result) {
    return mysql_fetch_array($result, MYSQL_ASSOC);
  }
  
  function db_query($sql) {
    global $queries;
    //echo '<!--' . $sql . '-->'; 
    $queries[] = $sql;
    $result    = mysql_query($sql);
    $error     = mysql_error();
    if ($error) {
      print_r($error);
      exit;
    }
    return $result;
  }
  
  function db_insert_id() {
    return mysql_insert_id();
  }
  
  function db_fetch_all($sql) {
    $datas  = array();
    $result = db_query($sql);
    while ($data = db_fetch_array($result)) {
      $datas[] = $data;
    }
    return $datas;
  }
  
  function db_fetch($sql) {
    return db_fetch_array(db_query($sql));
  }
  
  function db_insert($table, $data) {
    return db_perform($table, $data, 'insert');
  }
  
  function db_update($table, $data, $parameters = '') {
    return db_perform($table, $data, 'update', $parameters);
  }

  function db_perform($table, $data, $action = 'insert', $parameters = '', $link = '???') {
    reset($data);
    if ($action == 'insert') {
      $query = 'insert into ' . $table . ' (';
      while (list($columns, ) = each($data)) {
        $query .= $columns . ', ';
      }
      $query = substr($query, 0, -2) . ') values (';
      reset($data);
      while (list(, $value) = each($data)) {
        switch ((string)$value) {
          case 'now()':
            $query .= 'now(), ';
            break;
          case 'null':
            $query .= 'null, ';
            break;
          default:
            $query .= '\'' . db_escape($value) . '\', ';
            break;
        }
      }
      $query = substr($query, 0, -2) . ')';
    } elseif ($action == 'update') {
      $query = 'update ' . $table . ' set ';
      while (list($columns, $value) = each($data)) {
        switch ((string)$value) {
          case 'now()':
            $query .= $columns . ' = now(), ';
            break;
          case 'null':
            $query .= $columns .= ' = null, ';
            break;
          default:
            $query .= $columns . ' = \'' . db_escape($value) . '\', ';
            break;
        }
      }
      $query = substr($query, 0, -2) . ' where ' . $parameters;
    }
    return db_query($query);
  }
  
  function db_escape($string) {
    return mysql_real_escape_string($string);
  }
  